let data = {};
let editingId = null;
let requestUrl = null;
let wearArray = ["&emsp;&emsp;镶&ensp;嵌&emsp;&emsp;", "&emsp;&emsp;取&ensp;下&emsp;&emsp;"];

function addHandler() {
	let roleId = $("#role_id").combogrid("getValue");
	let categoryId = $("#category_id").combobox("getValue");

	if (roleId) {
		$("#roleId").combogrid("setValue", roleId);
	}
	if (categoryId) {
		$("#categoryId").combobox("setValue", categoryId);
	}

	$("#grade").numberspinner("setValue", 0);

	requestUrl = "/xingshi/insert";

	$("#xingshi_dialog").dialog("open");
}

function editHandler() {
	let rowData = $("#xingshi_list").datagrid("getSelected");
	
	if (rowData) {
		requestUrl = "/xingshi/updateById";

		$("#id").val(rowData.id);
		$("#roleId").combogrid("setValue", rowData.roleId);
		$("#grade").numberspinner("setValue", rowData.grade);
		$("#score").numberspinner("setValue", rowData.score);
		$("#categoryId").combobox("setValue", rowData.categoryId);
		$("#equipmentId").combogrid("setValue", rowData.equipmentId);
		$("#propertyValue").numberspinner("setValue", rowData.propertyValue);

		$("#xingshi_dialog").dialog("open");
	} else {
		alertMsg("请选择要修改的记录！", "warning");
	}
}

function fulingHandler() {
	let rowData = $("#xingshi_list").datagrid("getSelected");
	
	if (rowData) {
		$("#fuling_list").datagrid("reload", {
			xingshiId: rowData.id
		});

		$("#fuling_dialog").dialog("open");
	} else {
		alertMsg("请选择一条记录！", "warning");
	}
}

function viewHandler() {
	// 清空附灵属性
	$("#property_white").empty();
	$("#property_fuling").empty().hide();
	$("#property_xianghun").empty();

	let rowData = $("#xingshi_list").datagrid("getSelected");

	if (rowData) {
		// 宠物装备详情——基本信息
		ajaxGet("/xingshi_category/selectById", {
			id: rowData.categoryId
		}, function(resp) {
			let data = resp.data;

			$("#type_xingshi").html("星石");
			$("#name_xingshi").html(data.name);
			$("#note_xingshi").html(data.note);
			$("#grade_xingshi").html(rowData.grade);
			$("#image_xingshi").attr("src", data.image);

			ajaxGet("/property/selectById", {
				id: data.propertyId
			}, function (resp) {
				let result = resp.data;
				let attribute = "&emsp;" + rowData.grade + "级" + data.name;

				attribute += "&ensp;" + result.name + "&ensp;+" + rowData.propertyValue;

				$("#property_white").html(attribute);
			});

			ajaxGet("/chongwu_equipment_xingshi/selectInlay", {
				xingshiId: data.id
			}, function (resp) {
				let data = resp.data;

				if (data && data.length > 0) {
					let content = "";

					for (let i = 0; i < data.length; i++) {
						let name = data[i];

						content += name;

						if (i < data.length - 1) {
							content += "、";
						}
					}

					$("#inlay_xingshi").html(content);
				}
			});
		}, error);

		// 查询星石附灵属性
		ajaxGet("/xingshi_fuling/selectAttributes", {
			xingshiId: rowData.id,
		}, function(resp) {
			let data = resp.data;

			if(data && data.length > 0) {
				let content = "";

				for(let i = 0; i < data.length; i++) {
					let attribute = data[i];

					content += "&emsp;" + attribute.propertyName + "&ensp;+" + attribute.propertyValue;
				}

				$("#property_fuling").append(content).show();
			}
		}, error);

		// 查询星石的相魂属性
		ajaxGet("/xingshi_xianghun/selectByXingshiId", {
			xingshiId: rowData.id
		}, function(resp) {
			let data = resp.data;

			if(data) {
				$("#property_xianghun").html("&emsp;" + data.effect).show();
			}
		}, error);

		$("#inlay").linkbutton({
			text: wearArray[rowData.inlayStatus]
		})

		$("#score_xingshi").html(rowData.score);

		$("#xingshi_detail").dialog("open");
	} else {
		unselected();
	}
}

function deleteHandler() {
	let rowData = $("#xingshi_list").datagrid("getSelected");

	if (rowData) {
		$.messager.confirm("提示", "是否确认删除？", function(bool) {
			if (bool) {
				ajaxPost("/xingshi/deleteById", {
					id: rowData.id
				}, function(resp) {
					showMsg(resp.message);

					$("#xingshi_list").datagrid("reload");
				}, error);
			}
		});
	} else {
		alertMsg("请选择要删除的记录！");
	}
}

function computeHandler() {
	let rowData = $("#xingshi_list").datagrid("getSelected");

	if (rowData) {
		ajaxPost("/xingshi/compute", {
			xingshiId: rowData.id
		}, function(resp) {
			showMsg(resp.message);

			$("#xingshi_list").datagrid("reload");
		}, error);
	} else {
		unselected();
	}
}

$(document).ready(function() {

	/**
	 * 角色
	 */
	$("#role_id").combobox({
		url: "/role_account/selectAll",
		valueField: "id",
		textField: "name",
		width: 150,
		panelWidth: 150,
		prompt: "-选择角色-",
		panelHeight: "auto",
		formatter: function(row) {
			ajaxGet("/role_category/selectById", {
				id: row.categoryId
			}, function(resp) {
				let data = resp.data;

				$("#modeling_" + row.id).attr({
					"title": data.name,
					"src": data.image,
					"alt": data.name
				});
			}, error);

			return "<img height='20' id='modeling_" + row.id + "' />&ensp;" + row.name;
		}
	});

	/**
	 * 装备类型
	 */
	$("#category_id").combobox({
		url: "/xingshi_category/selectAll",
		valueField: "id",
		textField: "name",
		width: 150,
		panelHeight: "auto",
		prompt: "-选择类型-",
		formatter: function(row) {
			return "<img width='20' src='" + row.image + "' />&nbsp;" + row.name;
		}
	});

	/**
	 * 宠物装备
	 */
	$("#equipment_id").combogrid({
		url: "/chongwu_equipment/selectAll",
		method: "get",
		idField: "id",
		textField: "id",
		width: 150,
		panelWidth: 480,
		panelHeight: "auto",
		prompt: "-选择装备-",
		columns: [[
			{field: "categoryId", title: "装备类型", align: "center", width: 80
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/chongwu_equipment_category/selectById", {
						id: value
					}, function(resp) {
						$("#_category_" + rowIndex).attr("src", resp.data.image);
					}, error);

					return "<img height='" + size + "' id='_category_" + rowIndex + "' />";
				}
			},
			{field: "score", title: "评分", align: "center", width: 50},
			{field: "forger", title: "打造者", align: "center", width: 120},
			{field: "taozhuangId", title: "套装", align: "center", width: 120
				, formatter: function(value, rowData, rowIndex) {
					if(!value || value === 1) {
						return "<div>无</div>";
					} else {
						ajaxGet("/chongwu_taozhuang_category/selectById", {
							id: value
						}, function(resp) {
							let data = resp.data;

							$("#_taozhuang_" + rowIndex).html(data.name);
						}, error);

						return "<div class='blue' id='_taozhuang_" + rowIndex + "'></div>";
					}
				}
			},
			{field: "waiguanId", title: "外观", align: "center", width: 100
				, formatter: function(value, rowData, rowIndex) {
					if(value === 1) {
						return "<div>无</div>";
					} else {
						ajaxGet("/chongwu_waiguan_category/selectById", {
							id: value
						}, function(resp) {
							let data = resp.data;

							$("#_waiguan_" + rowIndex).html(data.name);
						}, error);

						return "<div class='blue' id='_waiguan_" + rowIndex + "'></div>";
					}
				}
			}
		]]
	});

	$("#search").linkbutton({
		iconCls: "icon-search"
	}).click(function() {
		let roleId = $("#role_id").combobox("getValue");
		let categoryId = $("#category_id").combobox("getValue");
		let equipmentId = $("#equipment_id").combogrid("getValue");
		
		$("#xingshi_list").datagrid("reload", {
			roleId: roleId,
			categoryId: categoryId,
			equipmentId: equipmentId
		});
	});

	$("#clear").linkbutton({
		iconCls: "icon-delete"
	}).click(function() {
		$("#search_form").form("clear");
	});

	/******************************************************************************************************/

	/**
	 * 装备类型
	 */
	$("#categoryId").combobox({
		url: "/xingshi_category/selectAll",
		valueField: "id",
		textField: "name",
		width: 150,
		required: true,
		panelHeight: "auto",
		formatter: function(row) {
			return "<img width='20' src='" + row.image + "' />&nbsp;" + row.name;
		}
	});

	$("#grade").numberspinner({
        min: 0,
        max: 10,
        width: 150,
        required: true
    });
	
	$("#propertyValue").numberspinner({
        width: 150,
        required: true
    });
	
	$("#score").numberspinner({
        min: 0,
		value: 0,
        width: 150,
        required: false
    });
	
	$("#equipmentId").combogrid({
        url: "/chongwu_equipment/selectAll",
		method: "get",
        idField: "id",
		textField: "id",
		width: 150,
		panelWidth: 540,
		panelHeight: "auto",
		columns: [[
			{field: "categoryId", title: "装备类型", align: "center"
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/chongwu_equipment_category/selectById", {
						id: value
					}, function(resp) {
						let data = resp.data;

						$("#category_" + rowIndex).attr({
							"alt": data.name,
							"src": data.image,
							"title": data.name
						});
					}, error);
					
					return "<img height='" + size + "' id='category_" + rowIndex + "' />";
				}
			},
			{field: "score", title: "评分", align: "center"},
			{field: "forger", title: "打造者", align: "center", width: 130},
			{field: "taozhuangId", title: "套装", align: "center", width: 150
				, formatter: function(value, rowData, rowIndex) {
					if(value === 1) {
						return "<div>无</div>";
					} else {
						ajaxGet("/chongwu_taozhuang_category/selectById", {
							id: value
						}, function(resp) {
							let data = resp.data;

							$("#taozhuang_" + rowIndex).html(data.name);
						}, error);
						
						return "<div class='blue' id='taozhuang_" + rowIndex + "'></div>";
					}
				}
			},
			{field: "waiguanId", title: "外观", align: "center", width: 150
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/chongwu_waiguan_category/selectById", {
						id: value
					}, function(resp) {
						let data = resp.data;

						$("#waiguan_" + rowIndex).html(data.name);
					}, error);

					return "<div class='blue' id='waiguan_" + rowIndex + "'></div>";
				}
			}
		]]
    });

	$("#roleId").combogrid({
		url: "/role_account/selectAll",
		idField: "id",
		textField: "name",
		width: 150,
		required: true,
		panelWidth: 440,
		panelHeight: "auto",
		columns: [[
			{field: "id", title: "角色ID", align: "center", width: 100},
			{field: "name", title: "角色名", align: "center", width: 120},
			{field: "categoryId", title: "角色造型", align: "center", width: 70
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/role_category/selectById", {
						id: value
					}, function(resp) {
						let data = resp.data;

						$("#role_modeling_" + rowIndex).attr({
							"alt": data.name,
							"src": data.image,
							"title": data.name
						});
					}, error);

					return "<img height='32' id='role_modeling_" + rowIndex + "' />";
				}
			},
			{field: "grade", title: "等级", align: "center", width: 50},
			{field: "schoolId", title: "门派", align:"center", width: 50
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/school/selectById", {
						id: value
					}, function(resp) {
						let data = resp.data;

						$("#_school_" + rowIndex).attr({
							"alt": data.name,
							"src": data.image,
							"title": data.name
						});
					}, error);

					return "<img height='32' id='_school_" + rowIndex + "' />";
				}
			}
		]]
	});
	
	$("#xingshi_dialog").dialog({
		title: "星石信息",
		width: 500,
		height: 300,
		buttons: [{
			iconCls: "icon-save",
			text: "保存",
			handler: function() {
				let selector = "#xingshi_form";

				checkForm(selector, function () {
					let data = $(selector).serialize();

					ajaxPost(requestUrl, data, function(resp) {
						showMsg(resp.message);

						$(selector).form("clear");
						$("#xingshi_dialog").dialog("close");
						$("#xingshi_list").datagrid("reload");
					}, error);
				});
			}
		}, {
			iconCls: "icon-cancel",
			text: "取消",
			handler: function() {
				$("#xingshi_dialog").dialog("close");
				$("#xingshi_form").form("clear");
			}
		}]
	});

	/******************************************************************************************************/

	$("#fuling_list").datagrid({
		url: "/xingshi_fuling/selectByXingshiId",
		method: "get",
		title: "星石附灵属性列表",
		width: 480,
		height: 300,
		onAfterEdit: function (rowIndex, rowData, changes) { // 结束行内编辑事件
			data = {
				id: rowData.id,
				xingshiId: rowData.xingshiId,
				step: changes.step ? changes.step : rowData.step,
				propertyId: changes.propertyId ? changes.propertyId : rowData.propertyId,
				propertyValue: changes.propertyValue ? changes.propertyValue : rowData.propertyValue
			};
		},
		toolbar: [{
			iconCls: "icon-add",
			text: "添加",
			handler: function() {
				let row = $("#xingshi_list").datagrid("getSelected");

				if(row) {
					let datagrid = $("#fuling_list");

					datagrid.datagrid("appendRow",{
						id: null,
						step: null,
						xingshiId: row.id,
						propertyId: null,
						propertyValue: 0
					});

					let total = datagrid.datagrid("getRows").length;

					editingId = total - 1;
					requestUrl = "/xingshi_fuling/insert";

					datagrid.datagrid("beginEdit", editingId);
				} else {
					unselected("请选择一件装备~");
				}
			}
		}, "-", {
			iconCls: "icon-edit",
			text: "修改",
			handler: function() {
				let datagrid = $("#fuling_list");

				if (editingId != null) {
					datagrid.datagrid("selectRow", editingId);
				} else {
					let row = datagrid.datagrid("getSelected");

					if (row) {
						// 获取行索引，这个索引从0开始
						let rowIndex = datagrid.datagrid("getRowIndex", row);

						editingId = rowIndex;
						requestUrl = "/xingshi_fuling/updateById";

						datagrid.datagrid("beginEdit", rowIndex);
					} else {
						unselected();
					}
				}
			}
		}, "-", {
			iconCls: "icon-save",
			text: "保存",
			handler: function() {
				if (editingId != null) {
					// 只有结束编辑才能获取到最新的值
					$("#fuling_list").datagrid("endEdit", editingId);

					ajaxPost(requestUrl, data, function(resp) {
						editingId = null;

						showMsg(resp.message);

						$("#fuling_list").datagrid("reload");
					}, error);
				}
			}
		}, "-", {
			iconCls: "icon-cancel",
			text: "取消",
			handler: function() {
				if (editingId != null) {
					$("#fuling_list").datagrid("cancelEdit", editingId);

					editingId = null;
				}
			}
		}, "-", {
			iconCls: "icon-delete",
			text: "删除",
			handler: function() {
				let rowData = $("#fuling_list").datagrid("getSelected");

				if(rowData) {
					$.messager.confirm("提示", "是否确认删除？", function(bool) {
						if (bool) {
							ajaxPost("/xingshi_fuling/deleteById", {
								id: rowData.id
							}, function(resp) {
								showMsg(resp.message);

								$("#fuling_list").datagrid("reload");
							}, error);
						}
					});
				} else {
					alertMsg("请选择一条记录！", "info");
				}
			}
		}],
		columns: [[
			{field: "id", title: "编号", align: "center", hidden: true},
			{field: "propertyId", title: "属性", align: "center", width: 150
				, editor: {
					type: "combobox",
					options: {
						url: "/property/selectByType?type=2",
						valueField: "id",
						textField: "name",
						panelHeight: "auto"
					}
				}
				, formatter: function(value, rowData, rowIndex) {
					if (value) {
						ajaxGet("/property/selectById", {
							"id": value
						}, function (resp) {
							let data = resp.data;

							$("#attribute_" + rowIndex).html(data.name);
						}, error);

						return "<div class='blue' id='attribute_" + rowIndex + "'></div>";
					}
				}
			},
			{field: "propertyValue", title: "属性值", align: "center", width: 150, editor: {
					type: "numberspinner",
					options: {
						min: 2,
						max: 5
					}
				}
			},
			{field: "step", title: "阶数", align: "center", width: 150, editor: {
					type: "numberspinner",
					options: {
						min: 1,
						max: 3
					}
				}
			},
			{field: "xingshiId", title: "星石", hidden: true}
		]]
	});

	$("#fuling_dialog").dialog({
		title: " ",
		height: 340
	});

	/******************************************************************************************************/

	$("#improve").linkbutton({
		text: "&emsp;&emsp;升&ensp;级&emsp;&emsp;"
	}).click(function() {
		unopen();
	});

	$("#inlay").linkbutton({
		text: "&emsp;&emsp;取&ensp;下&emsp;&emsp;"
	}).click(function() {
		let rowData = $("#xingshi_list").datagrid("getSelected");

		if (rowData) {
			if (rowData.inlayStatus === 1) {
				ajaxPost("/xingshi/inlay", {
					xingshiId: rowData.id
				}, function (resp) {
					showMsg(resp.message);

					$("#xingshi_list").datagrid("reload");
				});
			} else {
				unopen();
			}
		}
	});

	$("#xingshi_detail").dialog({
		title: "星石详情",
		width: 234
	});

	/******************************************************************************************************/

	/**
	 * 表格体的高度
	 * @type {number}
	 */
	let heigt_body = heigt_tr_with_role_details * 10;
	/**
	 * 表格高度
	 * @type {number}
	 */
	let height_table = heigt_tool + heigt_header + heigt_body + heigt_footer + heigt_scoll_bar + 2;

	$("#xingshi_list").datagrid({
		url: "/xingshi/selectByPage",
		height: height_table,
		fitColumns: true,
		rownumbers: true,
		pagination: true,
		toolbar: [{
			iconCls: "icon-add",
			text: "添加",
			handler: function() {
				addHandler();
			}
		}, "-", {
			iconCls: "icon-edit",
			text: "修改",
			handler: function() {
				editHandler();
			}
		}, "-", {
			iconCls: "icon-shield",
			text: "附灵",
			handler: function() {
				fulingHandler();
			}
		}, "-", {
			iconCls: "icon-search",
			text: "查看",
			handler: function() {
				viewHandler();
			}
		}, "-", {
			iconCls: "icon-delete",
			text: "删除",
			handler: function() {
				deleteHandler();
			}
		}, "-", {
			iconCls: "icon-ok",
			text: "计算评分",
			handler: function() {
				computeHandler();
			}
		}],
		columns: [[
			{field: "id", hidden: true},
			{field: "categoryId", title: "星石类型", align: "center", width: 160
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/xingshi_category/selectById", {
						id: value
					}, function(resp) {
						let data = resp.data;

						$("#xingshi_category_" + rowIndex).attr({
							"alt": data.name,
							"src": data.image,
							"title": data.name
						});
					}, error);
					
					return "<img height='" + size + "' id='xingshi_category_" + rowIndex + "' />";
				}
			},
			{field: "grade", title: "等级", align: "center", width: 160, sortable: true},
			{field: "score", title: "评分", align: "center", width: 160, sortable: true},
			{field: "propertyValue", title: "属性", align: "center", width: 160},
			{field: "equipmentId", title: "宠物装备", align: "center", width: 160
				, formatter: function(value, rowData, rowIndex) {
					if (!value) {
						return "<div> 无</div>";
					} else {
						ajaxGet("/chongwu_equipment/selectById", {
							id: value
						},function(resp) {
							let data = resp.data;

							ajaxGet("/chongwu_equipment_category/selectById", {
								id: data.categoryId
							},function(resp) {
								let data = resp.data;

								$("#equipment_" + rowIndex).attr({
									"alt": data.name,
									"src": data.image,
									"title": data.name
								});
							}, error);
						}, error);

						return "<img height='" + size + "' id='equipment_" + rowIndex + "' />";
					}
				}
			},
			roleDetailsColumn
		]]
	});

});